package com.hongye.consult.config;

import com.fasterxml.jackson.annotation.JsonBackReference;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@ServerEndpoint(value = "/websocket/{userName}")
@Component
public class WebSocketService implements Serializable {

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    @JsonBackReference
    private static Map<String, WebSocketService> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收userName
     */
    private String userName = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userName") String userName) {
        this.session = session;
        this.userName = userName;
        webSocketMap.put(userName, this);
        System.err.println("----------------------------------------------------------------------------");
        System.err.println("用户连接:" + userName + ":" + userName + ",当前在线人数为:" + webSocketMap.size());
        sendMessage("来自后台的反馈：连接成功");
        webSocketMap.forEach((k, v) -> System.err.println(k));
    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("userName") String userName) {
        if (webSocketMap.containsKey(userName)) {
            webSocketMap.remove(userName);
        }
        System.err.println("----------------------------------------------------------------------------");
        System.err.println(userName + "用户退出,当前在线人数为:" + webSocketMap.size());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.err.println("收到用户消息:" + userName + ",报文:" + message);
        //可以群发消息
        //消息保存到数据库、redis
        if (message != null) System.err.println("");
    }

    /**
     * 连接失败调用方法
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.err.println("用户错误:" + this.userName + ",原因:" + error.getMessage());
        error.printStackTrace();
    }


    /**
     * 连接服务器成功后主动推送
     */
    public void sendMessage(String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 向指定客户端发送消息
     * <p>
     * // * @param userName
     * //* @param message
     */
    public static void sendMessage(String userName, String message) {
        try {
            WebSocketService webSocketService = webSocketMap.get(userName);
            if (webSocketService != null) {
                webSocketService.getSession().getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }


  //下面方法根据自己情况 删 留
    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public static Map<String, WebSocketService> getWebSocketMap() {
        return webSocketMap;
    }

    public static void setWebSocketMap(Map<String, WebSocketService> webSocketMap) {
        WebSocketService.webSocketMap = webSocketMap;
    }

    public static void put(String key, WebSocketService data) {
        webSocketMap.put(key, data);
    }

    public static WebSocketService get(String key) {
        return webSocketMap.get(key);
    }

    public static void del(String key) {
        webSocketMap.remove(key);
    }
}